package org.firecloud.h5fun.controller.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonQuery;
import org.firecloud.h5fun.model.javabean.UserBean;
import org.json.JSONObject;
/**
 * 产生评论的HttpServlet通过Ajax方法调用URL：ajax_create_commentary<br>
 * 必须登陆：true<br>
 * 必须管理：false<br>
 * 参数：<br>
 * projectId，非必须，评论的project的ID<br>
 * appId，非必须，评论的Application的ID<br>
 * context，必须，评论的内容<br>
 * 注：projectId和appId必须有一个<br>
 * @author fc
 */
public class AjaxCreateCommentary extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject json = new JSONObject();
		Connection conn = null;
		try {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			CommonConfig config = (CommonConfig) req.getServletContext().getAttribute("commonConfig");
			UserBean loginUser = (UserBean) req.getSession().getAttribute("loginUser");
			if (loginUser != null) {
				int appId = 0;
				int projectId = 0;
				String strAppId = req.getParameter("appId");
				if (strAppId != null) {
					appId = Integer.parseInt(strAppId);
				}
				String strProjectId = req.getParameter("projectId");
				if (strProjectId != null) {
					projectId = Integer.parseInt(strProjectId);
				}
				String strContext = req.getParameter("context");
				if ((projectId != 0 || appId != 0)&&strContext!=null) {
					conn = config.getConn();
					CommonQuery.insert_commentary(conn, projectId, appId, loginUser.getId(), strContext);
					json.put("type", 0);
				} else {
					json.put("type", -3);
					json.put("msg", "无评论对象");
				}
			} else {
				json.put("type", -1);
				json.put("msg", "未登陆");
			}
		} catch (SQLException e) {
			json.put("type", -2);
			json.put("msg", "参数错误");
			e.printStackTrace();
		} catch (Exception e) {
			json.put("type", -4);
			json.put("msg", "未知错误");
			e.printStackTrace();
			Logger.getRootLogger().error(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (Exception e) {
					Logger.getRootLogger().error(e);
				}
			}
		}
		resp.getWriter().print(json);
	}
}
